package com.jeeplus.test.query.service.impl;

import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.query.mapper.MenuQueryMapper;
import com.jeeplus.test.query.service.MenuQueryService;
import com.jeeplus.test.query.view.MenuTreeView;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MenuQueryServiceImpl implements MenuQueryService {
    private final MenuQueryMapper menuQueryMapper;
    private final OfficeMapper officeMapper;

    private final AdmissionInfoMapper admissionInfoMapper;

    private String treeType;

    @Override
    public List<MenuTreeView> queryMenuTree(Long officeId,String treeType) {  // 修改返回类型为List
        return buildTreeInfo(officeId,treeType);  // 直接返回列表
    }

    /**
     * 构建树信息（现在返回列表）
     */
    private List<MenuTreeView> buildTreeInfo(Long officeId,String treeType) {
        // 根据officeId查询type
        Office office = officeMapper.selectById(officeId);
        String type = office.getType();
        List<MenuTreeView> result = new ArrayList<>();
        this.treeType = treeType;


        if ("1".equals(type)) {
            // 构建教务处
            result.add(buildEducationCollege());
        } else if("2".equals(type)) {
            // 构建继续教育学院
            result.add(buildContinueCollege());
        } else if("3".equals(type)) {
            // 构建研究生学院
            result.add(buildGraduateCollege());
        } else if("6".equals(type)) {
            // 返回三个学院的集合
            if(buildEducationCollege() != null){
                result.add(buildEducationCollege());
            }
            if(buildContinueCollege() != null){
                result.add(buildContinueCollege());
            }
            if(buildGraduateCollege() != null){
                result.add(buildGraduateCollege());
            }
        }
        return result;
    }

    // 以下是各学院构建方法
    private MenuTreeView buildEducationCollege() {
        List<Map<String, String>> maps = menuQueryMapper.selectYearAndMajorName(this.treeType);
        // 如果查询结果为空，直接返回null
        if (maps == null || maps.isEmpty()) {
            return null;
        }
        // 检查是否存在非空的name字段
        boolean hasName = maps.stream().anyMatch(map -> map.get("name") != null && !map.get("name").isEmpty());
        if (hasName) {
            // 四层结构：gradation → year → major → nameList
            Map<String, Map<String, Map<String, List<String>>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.groupingBy(
                                                    map -> map.get("majorName"),
                                                    Collectors.mapping(
                                                            map -> map.get("name"),
                                                            Collectors.toList()
                                                    )
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("教务处")
                    .hierarchy(hierarchy)
                    .build();
        } else {
            // 三层结构：gradation → year → majorList
            Map<String, Map<String, List<String>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.mapping(
                                                    map -> map.get("majorName"),
                                                    Collectors.toList()
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("教务处")
                    .hierarchy(hierarchy)
                    .build();
        }
    }

    private MenuTreeView buildGraduateCollege() {
        List<Map<String, String>> maps = menuQueryMapper.selectGraduateSchoolYearAndMajorName(this.treeType);
        // 如果查询结果为空，直接返回null
        if (maps == null || maps.isEmpty()) {
            return null;
        }

        // 检查是否存在非空的name字段
        boolean hasName = maps.stream().anyMatch(map -> map.get("name") != null && !map.get("name").isEmpty());
        if (hasName) {
            // 四层结构：gradation → year → major → nameList
            Map<String, Map<String, Map<String, List<String>>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.groupingBy(
                                                    map -> map.get("majorName"),
                                                    Collectors.mapping(
                                                            map -> map.get("name"),
                                                            Collectors.toList()
                                                    )
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("研究生学院")
                    .hierarchy(hierarchy)
                    .build();
        } else {
            // 三层结构：gradation → year → majorList
            Map<String, Map<String, List<String>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.mapping(
                                                    map -> map.get("majorName"),
                                                    Collectors.toList()
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("研究生学院")
                    .hierarchy(hierarchy)
                    .build();
        }
    }

    private MenuTreeView buildContinueCollege() {
        List<Map<String, String>> maps = menuQueryMapper.selectContinuingEducationYearAndMajorName(this.treeType);
        // 如果查询结果为空，直接返回null
        if (maps == null || maps.isEmpty()) {
            return null;
        }
        // 检查是否存在非空的name字段
        boolean hasName = maps.stream().anyMatch(map -> map.get("name") != null && !map.get("name").isEmpty());
        if (hasName) {
            // 四层结构：gradation → year → major → nameList
            Map<String, Map<String, Map<String, List<String>>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.groupingBy(
                                                    map -> map.get("majorName"),
                                                    Collectors.mapping(
                                                            map -> map.get("name"),
                                                            Collectors.toList()
                                                    )
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("继续教育学院")
                    .hierarchy(hierarchy)
                    .build();
        } else {
            // 三层结构：gradation → year → majorList
            Map<String, Map<String, List<String>>> hierarchy = maps.stream()
                    .collect(
                            Collectors.groupingBy(
                                    map -> map.get("gradation"),
                                    Collectors.groupingBy(
                                            map -> map.get("admissionYear"),
                                            Collectors.mapping(
                                                    map -> map.get("majorName"),
                                                    Collectors.toList()
                                            )
                                    )
                            )
                    );
            return MenuTreeView.builder()
                    .collegeName("继续教育学院")
                    .hierarchy(hierarchy)
                    .build();
        }
    }

//    @Override
//    public Map<String, Object> queryMenuTree(String officeId, String treeType, boolean hasName) {
//        // 1. 查询当前机构
//        Office office = officeMapper.selectById(officeId);
//        if (office == null) {
//            throw new IllegalArgumentException("机构不存在");
//        }
//
//        // 2. 构建返回结果
//        Map<String, Object> result = new LinkedHashMap<>(); // 使用LinkedHashMap保持顺序
//        result.put("id", office.getId());
//        result.put("name", office.getName());
//        result.put("type", "office");
//
//        // 3. 判断是否为档案馆（type=6）
//        if ("6".equals(office.getType())) {
//            // 档案馆处理逻辑
//            List<Office> children = officeMapper.selectChildrenByParentIds(office.getId());
//            List<Map<String, Object>> childNodes = new ArrayList<>();
//
//            for (Office child : children) {
//                Map<String, Object> childNode = new LinkedHashMap<>();
//                childNode.put("id", child.getId());
//                childNode.put("name", child.getName());
//                childNode.put("type", "office");
//                childNodes.add(childNode);
//            }
//
//            result.put("children", childNodes);
//        } else {
//            // 非档案馆处理逻辑
//            Map<String, Map<String, List<String>>> hierarchy = buildHierarchyForOffice(officeId, treeType, hasName);
//            List<Map<String, Object>> formattedData = formatHierarchyData(hierarchy, hasName);
//            result.put("children", formattedData);
//        }
//
//        return result;
//    }

    /**
     * 将原始层次结构转换为前端友好格式
     */
    private List<Map<String, Object>> formatHierarchyData(
            Map<String, Map<String, List<String>>> hierarchy,
            boolean hasName) {
        List<Map<String, Object>> result = new ArrayList<>();

        for (Map.Entry<String, Map<String, List<String>>> gradationEntry : hierarchy.entrySet()) {
            Map<String, Object> gradationNode = new LinkedHashMap<>();
            gradationNode.put("id", gradationEntry.getKey());
            gradationNode.put("name", gradationEntry.getKey());
            gradationNode.put("type", "gradation");

            List<Map<String, Object>> yearNodes = new ArrayList<>();
            for (Map.Entry<String, List<String>> yearEntry : gradationEntry.getValue().entrySet()) {
                Map<String, Object> yearNode = new LinkedHashMap<>();
                yearNode.put("id", yearEntry.getKey());
                yearNode.put("name", yearEntry.getKey());
                yearNode.put("type", "year");

                List<Map<String, Object>> majorNodes = new ArrayList<>();
                for (String major : yearEntry.getValue()) {
                    Map<String, Object> majorNode = new LinkedHashMap<>();
                    majorNode.put("id", major);
                    majorNode.put("name", major);
                    majorNode.put("type", "major");

                    if (hasName) {
                        // 这里可以添加学生姓名数据
                        // majorNode.put("children", 学生列表);
                    }

                    majorNodes.add(majorNode);
                }

                yearNode.put("children", majorNodes);
                yearNodes.add(yearNode);
            }

            gradationNode.put("children", yearNodes);
            result.add(gradationNode);
        }

        return result;
    }
    /**
     * 构建单个机构的层次结构
     */
    private Map<String, Map<String, List<String>>> buildHierarchyForOffice(String officeId, String treeType, boolean hasName) {
        // 1. 根据 treeType 动态查询数据
        List<Map<String, String>> maps;
        switch (treeType) {
            case "1":
                maps = menuQueryMapper.selectAdmissionData(officeId); // 录取信息
                break;
            case "2":
                maps = menuQueryMapper.selectStudentChangeData(officeId); // 学籍变动
                break;
            case "3":
                maps = menuQueryMapper.selectArchivalData(officeId); // 档案信息
                break;
            case "4":
                maps = menuQueryMapper.selectGraduationData(officeId); // 毕业信息
                break;
            case "5":
                maps = menuQueryMapper.selectBkbsssData(officeId); // 就业信息
                break;
            case "6":
                maps = menuQueryMapper.selectMailingData(officeId); // 转递信息
                break;
            default:
                throw new IllegalArgumentException("无效的 treeType");
        }

        // 2. 使用 Stream 分组构建层次结构
        if (hasName) {
            return maps.stream()
                    .collect(Collectors.groupingBy(
                            map -> map.get("gradation"),
                            Collectors.groupingBy(
                                    map -> map.get("admissionYear"),
                                    Collectors.mapping(
                                            map -> map.get("majorName"),
                                            Collectors.toList()
                                    )
                            )
                    ));
        } else {
            return maps.stream()
                    .collect(Collectors.groupingBy(
                            map -> map.get("gradation"),
                            Collectors.groupingBy(
                                    map -> map.get("admissionYear"),
                                    Collectors.mapping(
                                            map -> map.get("majorName"),
                                            Collectors.toList()
                                    )
                            )
                    ));
        }
    }

    /**
     * 查询专业下的姓名列表（根据 treeType 动态选择表）
     */
    private Map<String, List<String>> queryNamesByMajor(String major, String treeType) {
        switch (treeType) {
            case "5":
                return menuQueryMapper.selectBkbsssNamesByMajor(major).stream()
                        .collect(Collectors.groupingBy(
                                name -> major,
                                Collectors.toList()
                        ));
            case "6":
                return menuQueryMapper.selectMailingNamesByMajor(major).stream()
                        .collect(Collectors.groupingBy(
                                name -> major,
                                Collectors.toList()
                        ));
            default:
                throw new IllegalArgumentException("无效的 treeType");
        }
    }
}